package com.example.tech34Base64.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Base64的使用：照片与字符串的转化
 */
public class Base64Util {

    private static Logger LOGGER = LoggerFactory.getLogger(Base64Util.class);

    /**
     * 根据文件路径获取base64
     *
     * @param path 文件地址
     * @return base64字符串
     */
    public static String getBase64ByPath(String path) {
        String base64 = null;
        try {
            File file = new File(path);
            if(file.exists() && file.isFile()){
                InputStream in = new FileInputStream(file);
                base64 = getBase64ByIS(in);
            }
        } catch (IOException e) {
            LOGGER.error("path获取base64失败："+e.getMessage(),e);
        }
        return base64 ;
    }

    /**
     * inputstream转为base64的图片字符
     * @param inputStream 文件流
     * @return base64字符串
     */
    public static String getBase64ByIS(InputStream inputStream) {
        byte[] data = null;
        try {
            data = new byte[inputStream.available()];
            inputStream.read(data);
        } catch (IOException e) {
            LOGGER.error("inputStream转化String失败：" + e.getMessage(), e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    LOGGER.error("inputStream转化String失败：关闭流文件失败：" + e.getMessage(), e);
                }
            }
        }
        //Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }

}
